import { ajax } from "../../utils/ajax";
const addAdmin = document.getElementById('addAdmin');
const littleMenu = document.getElementById('littleMenu');
const setting = document.getElementById('setting');
const avatar = document.getElementById('avatar');
const settingPwd = document.getElementById('settingPwd');
const pwdModal = document.getElementById('pwdModal');
const pwdForm = document.forms[0];
const logout = document.getElementById('logout');

//添加管理员事件绑定
addAdmin.onclick = addAdmin_click;
//登录状态下拉小菜单单击事件
littleMenu.onclick = littleMenu_click;
//设置密码模态框
settingPwd.onclick = settingPwd_click;
//修改密码表单事件
pwdForm.onsubmit = pwdForm_submit;
//关闭修改密码模态框
pwdForm.close.onclick = close_click;
//退出登录
logout.onclick = logout_click;

//添加管理员，点击判断权限，是否可以打开注册管理员的页面
function addAdmin_click() {

    ajax.get('get', '/api/admin/regVerity', '', localStorage.getItem('token')).then(result => {
        if (result.flag) {
            //修改iframe框架的src属性  
            targetMain.src = "./regAdmin.html";
            alert(result.msg);
        } else {
            alert(result.msg);
        }
    })
}
//登录状态下拉小菜单处理函数
function littleMenu_click() {
    if (setting.style.display == 'none') {
        setting.style.display = 'block';
    } else if (setting.style.display == 'block') {
        setting.style.display = 'none';
    }
}
//获取管理员用户名
ajax.get('get', '/api/admin/avatar', '', localStorage.getItem('token')).then(result => {
    if (result.flag) {
        littleMenu.innerText = result.data.username;
        avatar.src = `http://127.0.0.1:3000${result.data.avatar}`;
    }
})
//修改密码模态框处理函数
function settingPwd_click() {
    pwdModal.style.display = 'block';
}
//修改密码表单处理函数
function pwdForm_submit(e) {
    e.preventDefault();
    const oldPwd = pwdForm.oldPwd.value;
    const newPwd = pwdForm.newPwd.value;

    ajax.post('post', '/api/admin/changePwd', { oldPwd, newPwd }, localStorage.getItem('token')).then(result => {
        if (result.flag) {
            alert(result.msg);
            localStorage.removeItem('token');
            window.top.location.assign('../../index.html');
        } else {
            alert(result.msg);
            pwdForm.reset();
        }
    })

}
//关闭修改密码模态框处理函数
function close_click(e) {
    e.preventDefault();
    pwdForm.reset();
    pwdModal.style.display = 'none';
}
//退出登录处理函数
function logout_click() {
    localStorage.removeItem('token');
    window.top.location.assign('../../index.html');
}

$(function () {
    for (let i = 0; i <= 10; i++) {
      $(`#menu dd:eq(${i}) a:first`).click(function () {
        $(`#menu dd:eq(${i}) .toggle`).stop().slideToggle();
      })
    }
  })